package com.m1905hd.user.web.controller
import com.m1905hd.common.global.JSONCode
import com.m1905hd.common.util.Page
import com.m1905hd.user.service.GuideService
import com.mongodb.BasicDBObject
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
/**
 * Created with IDEA
 * User:hxh
 * Date:16/4/23
 * Time:下午2:20
 */
@Controller
@RequestMapping("guide")
class GuideController {

    @Autowired
    GuideService guideService

    @RequestMapping("list")
    def showList() {
        return "guide/list"
    }

    @RequestMapping(value = "/list.json")
    def list(
            @RequestParam(defaultValue = "15") int limit, @RequestParam(defaultValue = "0") int pageIndex
    ) {
        pageIndex = pageIndex + 1
        def query = new BasicDBObject()
        Page page = this.guideService.list(query, new BasicDBObject("created", -1), null, pageIndex, limit)
        [results: page.count, rows: page.data]
    }

    @RequestMapping("add/{id}")
    def addNews(@PathVariable("id") int id, Model model) {
        def obj = [type: 1, status: 1] as BasicDBObject
        if (id != 0) {
            obj = guideService.findOne(id)
        }
        model.addAttribute("guide", obj)
        return "guide/addContent"
    }


    @RequestMapping(value = "edit", method = RequestMethod.POST)
    def edit(
            @RequestParam(defaultValue = "0") int id, int status,int type,String content) {
        def obj = [status: status,type:type,content:content] as BasicDBObject
        if (id == 0) {
            obj.created = System.currentTimeMillis()
            id = this.guideService.getCurrentId()
        }
        this.guideService.update(id, obj)
        return "redirect:list"
    }

    @RequestMapping("delete.json")
    def del(String ids) {
        ids.split(",").each {
            if (!StringUtils.isEmpty(it)) {
                this.guideService.del(Integer.parseInt(it))
            }
        }
        return [code: JSONCode.SUCCESS.code]
    }
}
